package cacco.jp.mld.panel.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cacco.jp.mld.panel.dao.UserDetailDao;

@Service
@Transactional
public class UserDetailServices implements UserDetailsService{

	@Autowired
    private UserDetailDao userDetailDao;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		return userDetailDao.loadUserByUsername(username);
	}
	public Collection<GrantedAuthority> getAuthorities(Integer access) {
		   // Create a list of grants for this user
		   List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
		    
		   // All users are granted with ROLE_USER access
		   // Therefore this user gets a ROLE_USER by default
		   authList.add(new GrantedAuthorityImpl("ROLE_USER"));
		    
		   // Check if this user has admin access 
		   // We interpret Integer(1) as an admin user
		   if ( access.compareTo(1) == 0) {
		    // User has admin access
		    authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		   }
		   // Return list of granted authorities
		   return authList;
		   }

}
